package com.probiz.estore.imports.handler.product;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.probiz.estore.catalog.service.ProductCategoryManager;
import com.probiz.estore.common.model.catalog.ProductCategory;
import com.probiz.estore.common.model.product.Product;
import com.probiz.estore.imports.handler.ColumnHandler;
import com.probiz.estore.imports.handler.basic.ColumnBasicHandler;
import com.probiz.estore.imports.model.Column;
import com.probiz.estore.imports.model.ImportModel;

public class CategoryNameHandler extends ColumnBasicHandler implements ColumnHandler{
	private Logger logger = Logger.getLogger(CategoryNameHandler.class);
	protected ProductCategoryManager	productCategoryManager	= null;
	
	public void setProductCategoryManager(ProductCategoryManager productCategoryManager) {
		this.productCategoryManager = productCategoryManager;
	}


	public void setProperty(ImportModel importModel, Column column)throws Exception {
		//特别注意：【商品目录完整路径】指定的目录比【商品目录名称】指定的目录的优先级要高！
		Product product=(Product)importModel.getTarget();
		String value = column.getValue();
		if(product.isUseSimplePathName()){
			//如果已经指定【商品目录完整路径】则跳过
			return;
		}	
		ProductCategory category =null;
		if(StringUtils.isNotBlank(value)){
			category =getCategoryByName(importModel,column.getValue());
		}
		if(importModel.getResult() == ImportModel.RESULT_ERROR){
			return ;
		}
		if(category !=null){
			//case:找到目录
			product.setCategory(category);
			importModel.setResult(ImportModel.RESULT_SUCCESS);
		}else{
			//case:找不目录
			if(product.getCategory()==null){
				//case:原目录为空
				importModel.setResult(ImportModel.RESULT_ERROR);
				String msg = "无法导入，因为没有找到相应的目录,请至少正确填写【商品目录完整路径】或【商品目录名称】中的一项";
				logger.error(msg);
				importModel.setMsg(msg);
				return;
			}else{
				//case:原目录不为空
				importModel.setResult(ImportModel.RESULT_SUCCESS);
			}
		}
		
	}
	
	
	private ProductCategory getCategoryByName(ImportModel importModel,String categoryName){
		List<ProductCategory> categoryList=productCategoryManager.getCategoryByName(categoryName);
		if(0 == categoryList.size()){
			//设置结果
			importModel.setResult(ImportModel.RESULT_ERROR);
			String msg = "找不到目录名称为【"+categoryName+"】的目录，无法导入";
			logger.error(msg);
			importModel.setMsg(msg);
			return null;
		}else if(1 == categoryList.size()){	
			return categoryList.get(0);
		}else{
			importModel.setResult(ImportModel.RESULT_ERROR);
			String msg = "找到多个目录名称均为【"+categoryName+"】的目录，系统无法识别";
			logger.error(msg);
			importModel.setMsg(msg);
			return null;
		}
		
	}
	
	

}
